package com.sx.pipeline.ui.supply.add

import android.Manifest
import android.content.Intent
import android.graphics.BitmapFactory
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ToastUtils
import com.loper7.date_time_picker.DateTimeConfig
import com.loper7.date_time_picker.dialog.CardDatePickerDialog
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.lxj.xpopup.XPopup
import com.permissionx.guolindev.PermissionX
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.app.base.CYDataBindingBaseActivity
import com.sx.pipeline.app.config.Constant
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.custom.dialog.CustomCommonPicket
import com.sx.pipeline.custom.dialog.DialogPasswordInput
import com.sx.pipeline.databinding.ActSupplyAddBinding
import com.sx.pipeline.ui.supply.ReleaseSupplyVM
import com.sx.pipeline.utils.AndroidUtil
import com.sx.pipeline.utils.CompressHelper
import com.sx.pipeline.utils.GlideEngine
import com.sx.pipeline.utils.PermissionHelper


/**
 * @Author: YY
 * @Date: 2022/4/5
 * @Description: 发布供应
 */
@Route(path = RoutePath.Mine.SUPPLY_ADD)
class SupplyAddActivity : CYDataBindingBaseActivity<ActSupplyAddBinding, ReleaseSupplyVM>
    (R.layout.act_supply_add), View.OnClickListener {
    private var unitId = 0 //发起单位id
    private var serviceId: Int = 0 //服务id
    private var startTime: String = "" //开始时间
    private var endTime: String = "" //结束时间
    private var priceBi:Double = 0.0
    override fun initData() {
        super.initData()
        mBinding.setVariable(BR.onClick, this)
        mBinding.titleBar.leftView.setOnClickListener {
            finish()
        }
        //默认联系人
        mBinding.etPrincipal.setText(mViewModel.mModel.getUserData()?.userName)
        mBinding.etContactPhone.setText(mViewModel.mModel.getUserData()?.phone)

        //请求发起单位名称
        mViewModel.getUserUnit()
        //请求供应数据
        mViewModel.getSupply()
        //获取供应负责人
        mViewModel.getContacts()

        initUploadAttach()
    }

    override fun initViewObservable() {
        super.initViewObservable()
        //发起单位数据
        observe(mViewModel.userUnitEvent) {
            unitId = it?.id!!
            mBinding.sbUnit.rightText = it?.name
        }

        //上传的附件
        observe(mViewModel.uploadDataEvent) {
            mBinding.imageUploadAttachment.addImage(it)
        }

        //管币价格
        observe(mViewModel.supplyPriceEvent) {
            if (it != null) {
                priceBi = it
            }
            if (priceBi?.toInt()!=0){
                mBinding.tvCurrency.text = it.toString() + "管币"
                mBinding.tabPrice.visibility=View.VISIBLE
            }
        }
    }

    fun initUploadAttach() {
        // 上传图片
        mBinding!!.imageUploadAttachment.initAdapter(3, 3)
        mBinding!!.imageUploadAttachment.setImageUploadListener {
            PermissionHelper.requestTip(this,"上次图片需要授权相机和读写权限",object :
                PermissionUtils.SimpleCallback{
                override fun onGranted() {
                    PictureSelector.create(this@SupplyAddActivity)
                        .openGallery(SelectMimeType.ofImage())
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setMaxSelectNum(3 - mBinding.imageUploadAttachment.imagePath.size)
                        .forResult(object : OnResultCallbackListener<LocalMedia?> {
                            override fun onResult(result: ArrayList<LocalMedia?>?) {
                                //循环上传图片
                                for (i in 0 until result?.size!!) {
                                    Log.d("okhttp", "" + result[i]?.realPath)
                                    //压缩图片
                                    val inputBitmap =
                                        BitmapFactory.decodeFile(result[i]?.realPath)
                                    val compressFile = CompressHelper.compressQuality(
                                        this@SupplyAddActivity,
                                        inputBitmap
                                    )
                                    mViewModel.uploadImage(compressFile)
                                }
                            }

                            override fun onCancel() {}
                        })
                }

                override fun onDenied() {
                    ToastUtils.showShort("请授权后再继续操作")
                }
            },Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA)

//            PermissionX.init(this)
//                .permissions(
//                    Manifest.permission.READ_EXTERNAL_STORAGE,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                    Manifest.permission.CAMERA
//                )
//                .onExplainRequestReason { scope, deniedList ->
//                    scope.showRequestReasonDialog(
//                        deniedList,
//                        "核心基础功能基于这些权限,请允许,否则影响app正常使用",
//                        "确认",
//                        "取消"
//                    )
//                }
//                .onForwardToSettings { scope, deniedList ->
//                    scope.showForwardToSettingsDialog(
//                        deniedList,
//                        "您需要手动在“设置”中允许必要的权限",
//                        "确定",
//                        "取消"
//                    )
//                }
//                .request { allGranted, grantedList, deniedList ->
//                    if (allGranted) {
//                        PictureSelector.create(this)
//                            .openGallery(SelectMimeType.ofImage())
//                            .setImageEngine(GlideEngine.createGlideEngine())
//                            .setMaxSelectNum(3 - mBinding.imageUploadAttachment.imagePath.size)
//                            .forResult(object : OnResultCallbackListener<LocalMedia?> {
//                                override fun onResult(result: ArrayList<LocalMedia?>?) {
//                                    //循环上传图片
//                                    for (i in 0 until result?.size!!) {
//                                        Log.d("okhttp", "" + result[i]?.realPath)
//                                        //压缩图片
//                                        val inputBitmap =
//                                            BitmapFactory.decodeFile(result[i]?.realPath)
//                                        val compressFile = CompressHelper.compressQuality(
//                                            this@SupplyAddActivity,
//                                            inputBitmap
//                                        )
//                                        mViewModel.uploadImage(compressFile)
//                                    }
//                                }
//
//                                override fun onCancel() {}
//                            })
//                    } else {
//                        ToastUtils.showShort(getString(R.string.txt_these_permissions_are_denied))
//                    }
//                }

        }
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            //选择标题
            R.id.sb_title -> {
                ARouter.getInstance().build(RoutePath.Service.SERVICE_CHOOSE)
                    .navigation(this, Constant.REQUEST_CHOOSE_SERVICE)
            }
            //选择结算方式
            R.id.sb_settlement_method -> {
                if (mViewModel.settleTypeData.size == 0) {
                    ToastUtils.showShort("未获取到数据")
                    return
                }
                val popup =
                    CustomCommonPicket(this, getString(R.string.txt_select_settlement_method))
                popup.setPickerData(mViewModel.settleTypeData)
                popup.setCommonPickerListener { _, data ->
                    mBinding.sbSettlementMethod.rightText = data
                }
                XPopup.Builder(this)
                    .borderRadius(42f)
                    .isDarkTheme(false)
                    .asCustom(popup)
                    .show()
            }
            R.id.sb_area -> {
//                //选择服务区域
//                showProvincesDialog()
            }
            //供应负责人
            R.id.iv_principal -> {
                if (mViewModel.taskContactData.size == 0) {
                    ToastUtils.showShort("未获取到数据")
                    return
                }
                val popup = CustomCommonPicket(this, getString(R.string.txt_chooose_supply_manager))
                popup.setPickerData(mViewModel.taskContactData)
                popup.setCommonPickerListener { position, data ->
                    mBinding.etPrincipal.setText(data)
                    mBinding.etContactPhone.setText(mViewModel.taskContactPhoneData[position])
                }
                XPopup.Builder(this)
                    .borderRadius(42f)
                    .isDarkTheme(false)
                    .asCustom(popup)
                    .show()
            }
            R.id.sb_start_time -> {
                CardDatePickerDialog.builder(this)
                    .setTouchHideable(true)
                    .showBackNow(false)
                    .setMinTime(System.currentTimeMillis())
                    .showFocusDateInfo(false)
                    .setWrapSelectorWheel(false)
                    .setTitle("选择开始时间")
                    .showDateLabel(true)
                    .setBackGroundModel(CardDatePickerDialog.STACK)
                    .setDisplayType(
                        DateTimeConfig.YEAR,
                        DateTimeConfig.MONTH,
                        DateTimeConfig.DAY,
                        DateTimeConfig.HOUR,
                        DateTimeConfig.MIN,
                    )
                    .setLabelText("年", "月")
                    .setOnChoose("选择") {
                        startTime = AndroidUtil.conversionTime(it, "yyyy-MM-dd HH:mm")
                        mBinding.sbStartTime.rightText =
                            AndroidUtil.conversionTime(it, "yyyy-MM-dd HH:mm")

                        if (!TextUtils.isEmpty(endTime)) {
                            //请求计算管币 价格
                            mViewModel.getSupplyPrice(serviceId, startTime, endTime)
                        }
                    }
                    .setOnCancel("关闭") {

                    }
                    .build().show()
            }
            R.id.sb_end_time -> {
                CardDatePickerDialog.builder(this)
                    .setTouchHideable(true)
                    .showBackNow(false)
                    .setMinTime(System.currentTimeMillis())
                    .setMaxTime(System.currentTimeMillis()+172800000)
                    .showFocusDateInfo(false)
                    .setWrapSelectorWheel(false)
                    .setTitle("选择结束时间")
                    .showDateLabel(true)
                    .setBackGroundModel(CardDatePickerDialog.STACK)
                    .setDisplayType(
                        DateTimeConfig.YEAR,
                        DateTimeConfig.MONTH,
                        DateTimeConfig.DAY,
                        DateTimeConfig.HOUR,
                        DateTimeConfig.MIN,
                    )
                    .setLabelText("年", "月")
                    .setOnChoose("选择") {
                        endTime = AndroidUtil.conversionTime(it, "yyyy-MM-dd HH:mm")
                        mBinding.sbEndTime.rightText =
                            AndroidUtil.conversionTime(it, "yyyy-MM-dd HH:mm")
                        if (!TextUtils.isEmpty(startTime) && !TextUtils.isEmpty(endTime)) {
                            //请求计算管币 价格
                            mViewModel.getSupplyPrice(serviceId, startTime, endTime)
                        }
                    }
                    .setOnCancel("关闭") {

                    }
                    .build().show()
            }
            R.id.tv_commit -> {
                if (TextUtils.isEmpty(mBinding.sbTitle.rightText.toString())) {
                    ToastUtils.showShort("请选择供应标题")
                    return
                }
                if (TextUtils.isEmpty(mBinding.etPrincipal.text.toString())) {
                    ToastUtils.showShort("请选择供应负责人")
                    return
                }
                if (TextUtils.isEmpty(mBinding.etContactPhone.text.toString())) {
                    ToastUtils.showShort("请输入负责人联系电话")
                    return
                }
                if (TextUtils.isEmpty(startTime)) {
                    ToastUtils.showShort("请选择开始时间")
                    return
                }
                if (TextUtils.isEmpty(endTime)) {
                    ToastUtils.showShort("请选择结束时间")
                    return
                }
                if (TextUtils.isEmpty(mBinding.sbSettlementMethod.rightText.toString())) {
                    ToastUtils.showShort("请选择结算方式")
                    return
                }
//                if (mViewModel.mModel.getPayWord()==false){
//                    ARouter.getInstance().build(RoutePath.Setting.MODIFY_LOGIN_PASS).withInt("type",1).navigation()
//                    return;
//                }
                if (priceBi.toInt()!=0){
                    val popup =
                        DialogPasswordInput(this, priceBi.toString()).setPassInputListener { pass ->
                            mViewModel.supplyOrderAdd(
                                serviceId,
                                mBinding.sbTitle.rightText.toString(),
                                mBinding.etDesc.text.toString(),
                                startTime,
                                endTime,
                                mBinding.etPrincipal.text.toString(),
                                mBinding.etContactPhone.text.toString(),
                                mBinding.sbSettlementMethod.rightText.toString(),
                                AndroidUtil.listToString(mBinding.imageUploadAttachment.imagePath)
                                    .toString(),
                                pass
                            )
                        }
                    XPopup.Builder(this)
                        .borderRadius(42f)
                        .isDarkTheme(false)
                        .asCustom(popup)
                        .show()
                }else{
                    mViewModel.supplyOrderAdd(
                        serviceId,
                        mBinding.sbTitle.rightText.toString(),
                        mBinding.etDesc.text.toString(),
                        startTime,
                        endTime,
                        mBinding.etPrincipal.text.toString(),
                        mBinding.etContactPhone.text.toString(),
                        mBinding.sbSettlementMethod.rightText.toString(),
                        AndroidUtil.listToString(mBinding.imageUploadAttachment.imagePath)
                            .toString(),
                        ""
                    )
                }


            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK) return
        when (requestCode) {
            //修改服务
            Constant.REQUEST_CHOOSE_SERVICE -> {
                serviceId = data?.getIntExtra("serviceId", 0)!!
                val serviceName = data?.getStringExtra("serviceName").toString()
                val desc = data?.getStringExtra("desc").toString()
                val address = data?.getStringExtra("address").toString()
                val price = data?.getStringExtra("price").toString()
                val images = data?.getStringExtra("images").toString()
                //设备标题名称
                mBinding.sbTitle.rightText = serviceName
                mBinding.etDesc.setText(desc)
                mBinding.sbArea.rightText = address
                mBinding.sbPrice.rightText = "¥$price"
                if (!TextUtils.isEmpty(images)) {
                    mBinding.imageUploadAttachment.clearImage()
                    val imageList = images.split(",")
                    for (i in imageList) {
                        mBinding.imageUploadAttachment.addImage(i)
                    }
                }
            }
        }
    }
}